<template>
	<view class="chat-container">
		<up-navbar :title="aiTitle" @leftClick="leftClick" safeAreaInsetTop placeholder></up-navbar>
		<view class="messages" ref="messagesContainer">
			<up-subsection :list="list" mode="subsection" :current="1" font-size="15" style="height: 30px"></up-subsection>
			<view class="message-item" v-for="(msg, index) in messages" :key="index">
				<view class="message" :class="{ 'user-message': msg.type === 'user', 'bot-message': msg.type === 'bot' }">
					<template v-if="msg.type === 'bot'">
						<image class="avatar" :src="botAvatar"></image>
						<ua-markdown class="content" :source="msg.content" />
					</template>
					<template v-else>
						<view class="content">{{ msg.content }}</view>
						<image class="avatar" :src="userAvatar"></image>
					</template>
				</view>
			</view>
			<view ref="bottom"></view>
		</view>
		<view class="input-container">
			<u-textarea v-model="userInput" maxlength="8000" count autoHeight height="20" @keypress.enter.prevent="sendMessage" placeholder="请输入消息..." class="input" />
			<button @click="sendMessage" class="send-button">发送</button>
		</view>
	</view>
</template>

<script>
import { chatWithAI } from '../../utils/apiService.js';

export default {
	data() {
		return {
			aiTitle: '聊天室',
			userInput: '',
			messages: [],
			userAvatar: '../../static/admin.jpg',
			botAvatar: '../../static/2.png',
			list: ['gpt-3.5-turbo', 'gpt-4o-mini', 'gpt-4o-plus']
		};
	},
	methods: {
		leftClick() {
			uni.navigateTo({
				url: '/pages/personal/onlineResumeView'
			});
		},
		async sendMessage() {
			if (this.userInput.trim() !== '') {
				this.messages.push({ type: 'user', content: this.userInput });
				const input = this.userInput;
				this.userInput = '';
				this.aiTitle = 'AI思考中...';
				await this.sendUserMessage(input);
			}
		},
		async sendUserMessage(input) {
			if (!input.trim()) return;

			let currentMessage = '';
			let simpleResponse = this.getSimpleResponse(input);
			if (simpleResponse) {
				this.aiTitle = '聊天室';
				this.messages.push({ type: 'bot', content: simpleResponse });
				return;
			}
			this.messages.push({ type: 'bot', content: '正在思考中...' });
			let length = this.messages.length - 1;
			try {
				await chatWithAI(input, (message) => {
					let chars = message.split();
					let index = 0;
					const interval = setInterval(() => {
						if (index < chars.length) {
							currentMessage += chars[index++];
							this.$set(this.messages, length, { type: 'bot', content: currentMessage });
						} else {
							clearInterval(interval);
						}
					}, 500);
				});
				this.aiTitle = '聊天室';
			} catch (error) {
				this.aiTitle = '聊天室';
				console.log(error);
				uni.showToast({ title: '错误: 无法获取 AI 响应', icon: 'none' });
				this.messages.push({ type: 'bot', content: '响应失败...' });
			}
		},
		getSimpleResponse(input) {
			const normalizedInput = input.toLowerCase();
			if (normalizedInput.includes('你好')) {
				return '你好！有什么我可以帮忙的吗？';
			} else if (normalizedInput.includes('你是谁')) {
				return '我是一个聊天机器人，可以回答你的问题！';
			} else if (normalizedInput.includes('今天天气怎么样')) {
				return '今天天气晴朗，适合出门！';
			} else if (normalizedInput.includes('几点')) {
				const currentTime = new Date();
				return `现在是 ${currentTime.getHours()}:${currentTime.getMinutes()}`;
			} else if (normalizedInput.includes('再见')) {
				return '再见！祝你有美好的一天！';
			}
			return null;
		}
	}
};
</script>

<style>
.chat-container {
	display: flex;
	flex-direction: column;
	height: 100vh;
	background-color: #f9f9f9;
}

.messages {
	flex: 1;
	overflow-y: auto;
	padding: 10px;
	background-color: #fff;
	border-radius: 8px;
	box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.message-item {
	margin-bottom: 10px;
}

.message {
	display: flex;
	margin-bottom: 10px;
}

.user-message {
	justify-content: flex-end;
}

.bot-message {
	justify-content: flex-start;
}

.avatar {
	width: 40px;
	height: 40px;
	border-radius: 50%;
	margin: 0 10px;
}

.content {
	max-width: 70%;
	padding: 10px;
	border-radius: 10px;
	background-color: #dcf8c6;
	word-wrap: break-word;
	box-shadow: 0 2px 3px rgba(0, 0, 0, 0.1);
}

.bot-message .content {
	background-color: #e1e1e1;
}

.input-container {
	display: flex;
	padding: 10px;
	border-top: 1px solid #ccc;
	background-color: #fff;
}

.input {
	flex: 1;
	padding: 10px;

	border: 1px solid #ccc;
	border-radius: 5px;
	transition: border-color 0.3s;
}

.input:focus {
	border-color: #007aff;
}

.send-button {
	margin-left: 10px;
	padding: 0 20px;
	height: 50px;
	border: none;
	background-color: #007aff;
	color: white;
	border-radius: 5px;
	cursor: pointer;
	transition: background-color 0.3s;
}

.send-button:hover {
	background-color: #0056b3;
}
</style>
